package com.itmuch.common.feignset.hystix;

import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


/**
 * ServletFilter for initializing HystrixRequestContext at the beginning of an HTTP request and shutting down at the end:
 *
 * The filter shuts down the HystrixRequestContext at the end of the request to avoid
 * leakage into subsequent requests.
 */
/**
 * 使用注解标注过滤器
 */

public class QfHystrixRequestContextEnablerFilter implements Filter {

	public static  Boolean  ENABLED_HYSTRIX_FILTER = false;
	
	private Logger log = LoggerFactory.getLogger(QfHystrixRequestContextEnablerFilter.class);

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void destroy() {
	}

	//socket监听去里面加入这个会报错吗，socket 里面调用别人的client的时候，也会调用这个的。但是这个会报错
	//所以要监听到，在拦截器
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest re = (HttpServletRequest) request;
		if (log.isDebugEnabled()) {
			log.info("QfHystrixRequestContextEnablerFilterThe before url  is >>>>>>>>>>>>>>" + re.getRequestURL());
		}
		HystrixRequestContext context = null;
		try{
			 context = HystrixRequestContext.initializeContext();
			chain.doFilter(request, response);
			if (log.isDebugEnabled()) {
				log.info("QfHystrixRequestContextEnablerFilter filter after url  is >>>>>>>>>>>>>>" + re.getRequestURL());
			}
		}catch (Exception e){
			e.printStackTrace();
			log.info("doFilter,e",e);
		}finally {
			if(context!=null){
				context.shutdown();
			}
		}
	}
}
